package midi.notation.util;


import midi.basic.Duration;
import midi.basic.Pitch;
import midi.notation.Note;
import midi.theory.PitchUtil;

import java.util.ArrayList;

public class NoteUtil {

    //把记谱法中的字符串转换成Note数据类型结构，notationString="w[C--,D,bbE++](velocity=100,off=true,text=我)"
    public static Note fromNoteString(String noteString) {
        //s1=w
        String s1 = noteString.split("\\[")[0];
        //s2=C--,D,bbE++
        String s2 = noteString.split("\\[")[1].split("\\]")[0];
        //s3=velocity=100,off=true,text=我)
        String s3 = noteString.split("\\(")[1];
        s3 = s3.substring(0, s3.length() - 1);
        //把音名存入并返回
        Note note = new Note();
        note.pitchList = new ArrayList<>();
        //判断休止符号
        if (s2.trim().equals("0")) {
            note.isRestingNote = true;
        } else {
            note.isRestingNote = false;
            for (String str : s2.split(",")) {
                Pitch pitch = PitchUtil.fromString(str);
                note.pitchList.add(pitch);
            }
        }
        //音符长度
        note.duration = Duration.fromDurationString(s1);
        //音符属性只处理了一个velocity
        int velocity = 100;
        for (String str : s3.split(",")) {
            if (str.startsWith("velocity")) {
                velocity = Integer.valueOf(str.split("=")[1]);
            }
        }
        note.velocity = velocity;
        return note;
    }

    //作用和上面相反
    public static String toNoteString(Note note) {
        String str = "";
        str += note.duration.getDesc() + "[";
        if (note.isRestingNote) {
            //休止符号
            str += "0";
        } else {
            //不是休止符号
            for (Pitch pitch : note.pitchList) {
                str += PitchUtil.toString(pitch) + ",";
            }
        }
        str = str.substring(0, str.length() - 1);
        str += "]";
        //只处理了一个速度参数属性
        str += "(";
        str += "velocity=" + note.velocity + ")";

        return str;
    }


}
